﻿using System;
using System.ComponentModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using VkVideoPlayer.UI.Services;
using VkontakteCore;
using VkontakteDataLayer;
using VkontakteInfrastructure.Interfaces;
using VkontakteInfrastructure.Model;

namespace VkVideoPlayer.UI.ViewModels
{
	public class ViewModelBase : INotifyPropertyChanged
	{
		public event PropertyChangedEventHandler PropertyChanged;


		public string AppTitle { get; set; }

		private User _user;
		public User User
		{
			get
			{
				if (_user == null)
				{
					var storage = new EntityStorage();
					_user = storage.LoadEntity<User>();
				}
				return _user;
			}
			set
			{
				_user = value;
				OnPropertyChange("User");
			}
		}


		public void OnPropertyChange(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		public bool IsPortraitOrientation
		{
			get
			{
				return Orientation == PageOrientation.Portrait ||
					Orientation == PageOrientation.PortraitUp ||
					Orientation == PageOrientation.PortraitDown;
			}
		}

		public bool IsLandscapeOrientation
		{
			get
			{
				return Orientation == PageOrientation.Landscape ||
					Orientation == PageOrientation.LandscapeLeft ||
					Orientation == PageOrientation.LandscapeRight;
			}
		}

		protected PageOrientation Orientation
		{
			get { return ((PhoneApplicationFrame)Application.Current.RootVisual).Orientation; }
		}

		protected Dispatcher Dispatcher
		{
			get { return Deployment.Current.Dispatcher; }
		}

		protected PhoneApplicationPage ApplicationPage;

		public virtual void OnNavigatedTo(PhoneApplicationPage page, NavigationEventArgs e)
		{

			ApplicationPage = page;
		}

		public virtual void OnNavigatedFrom(PhoneApplicationPage page, NavigationEventArgs e)
		{

		}
		private static IVkontakteApi vkontakteApi = null;
		protected T GetService<T>() where T : class
		{
			if (typeof(T) == typeof(IEntityDataStorage))
			{
				return new EntityStorage() as T;
			}

			if (typeof(T) == typeof(IVkontakteApi))
			{
				if (vkontakteApi == null) vkontakteApi = new VkontakteApi(GetService<IEntityDataStorage>());
				return vkontakteApi as T;
			}

			if (typeof(T) == typeof(INavigationService))
			{
				return new VKNavigationService() as T;
			}

			if (typeof(T) == typeof(IErrorHandlerService))
			{
				return new ErrorHandlerService(GetService<IVkontakteApi>(), GetService<INavigationService>()) as T;
			}
			throw new ArgumentException("Service not found");
		}

	}
}
